package com.wx.disparent.mallparent.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wx.disparent.mallparent.commons.util.PageResult;
import com.wx.disparent.mallparent.commons.util.PageUtil;
import com.wx.disparent.mallparent.commons.util.QRCodeUtil;
import com.wx.disparent.mallparent.entity.ParaEntity;
import com.wx.disparent.mallparent.entity.ProblemEntity;
import com.wx.disparent.mallparent.entity.UserEntity;
import com.wx.disparent.mallparent.service.FrontUserService;
import com.wx.disparent.mallparent.service.ParaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/front/user")
public class FrontUserController {

    @Value(value = "${file-location}")
    private String path;
    @Value(value = "${file-path-pattern}")
    private String filePatten;
    @Autowired
    private FrontUserService frontUserService;
    @Autowired
    private ParaService paraService;


    @RequestMapping(value = "/updatePw")
    public ModelAndView updatePw(@RequestParam(value = "id") Integer id) {
        UserEntity userEntity = frontUserService.findById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/updatePwPage");
        modelAndView.addObject("userEntity", userEntity);
        return modelAndView;
    }

    @RequestMapping(value = "/updatePwCheck", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updatePwCheck(UserEntity userEntity) {
        Map<String, Object> updatePwCheckMap = frontUserService.updatePwCheck(userEntity);
        return updatePwCheckMap;
    }

    @RequestMapping(value = "/sureUpdatePw", method = RequestMethod.POST)
    public ModelAndView sureUpdatePw(@RequestParam(value = "id") Integer id,
                                     @RequestParam(value = "newPw") String newPw,
                                     HttpSession httpSession) {
        UserEntity userEntity = new UserEntity();
        userEntity.setPasswd(newPw);
        userEntity.setId(id);
        int update = frontUserService.updatePassWdById(userEntity);
        UserEntity byId = frontUserService.findById(id);
        httpSession.setAttribute("userEntity", byId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/userDetail");
        modelAndView.addObject("userEntity", userEntity);
        modelAndView.addObject("SumWelfareMoney", frontUserService.SumWelfareMoney(id).getSumWelfareMoney());
        return modelAndView;

    }


    @RequestMapping(value = "/sureUpdate", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView sureUpdate(UserEntity userEntity, HttpSession httpSession) {
        Integer i = frontUserService.updateById(userEntity);
        UserEntity byId = frontUserService.findById(userEntity.getId());
        httpSession.setAttribute("userEntity", byId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/userDetail");
        modelAndView.addObject("userEntity", byId);
        modelAndView.addObject("SumWelfareMoney", frontUserService.SumWelfareMoney(userEntity.getId()).getSumWelfareMoney());
        return modelAndView;
    }


    @RequestMapping(value = "/userInfoCheck", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> userInfoCheck(UserEntity userEntity, HttpSession httpSession) {
        Map<String, Object> userInfoCheckMap = frontUserService.userInfoCheck(userEntity);
        return userInfoCheckMap;
    }

    @RequestMapping(value = "/userInfo")
    public ModelAndView userInfo(@RequestParam(value = "id") Integer id) {
        UserEntity userEntity = frontUserService.findById(id);
        List<ProblemEntity> problemEntityList = frontUserService.findAllProblem();
        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("paraid", "bankcard_type");
        List<ParaEntity> acctTypeParaEntityList = paraService.findAllAcctTypePara(paraMap);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/userInfo");
        modelAndView.addObject("userEntity", userEntity);
        modelAndView.addObject("problemEntityList", problemEntityList);
        modelAndView.addObject("acctTypeParaEntityList", acctTypeParaEntityList);
        return modelAndView;
    }

    @RequestMapping(value = "/userPath")
    public ModelAndView userPath(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        if (session.getAttribute("userEntity") == null) {
            modelAndView.setViewName("web/login");
            return  modelAndView;
        } else {
            UserEntity userEntity = (UserEntity) session.getAttribute("userEntity");
            userEntity = frontUserService.SumWelfareMoney(userEntity.getId());
            modelAndView.addObject("SumWelfareMoney",userEntity.getSumWelfareMoney());
            modelAndView.setViewName("web/userDetail");
            return modelAndView;
        }
    }

    @RequestMapping(value = "/paymentAccount")
    public ModelAndView paymentAccount(@RequestParam(value = "id") Integer id) {

        ModelAndView mv = new ModelAndView();
        UserEntity userEntity = frontUserService.findById(id);
        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("paraid", "bankcard_type");
        List<ParaEntity> acctTypeParaEntityList = paraService.findAllAcctTypePara(paraMap);
        mv.addObject("userEntity", userEntity);
        mv.addObject("acctTypeParaEntityList", acctTypeParaEntityList);
        mv.setViewName("web/payAccount");
        return mv;
    }

    /**
     * 绑定账号
     *
     * @param userEntity
     * @return
     */
    @RequestMapping(value = "/surePaymentAccount")
    public ModelAndView surePaymentAccount(UserEntity userEntity) {
        ModelAndView mv = new ModelAndView();
        frontUserService.updateByIdPayAcct(userEntity);
        mv.addObject("SumWelfareMoney", frontUserService.SumWelfareMoney(userEntity.getId()).getSumWelfareMoney());
        mv.setViewName("web/userDetail");
        return mv;
    }

    @RequestMapping(value = "/sureRegister", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> sureRegister(UserEntity userEntity) {
        Map<String, String> registerMap = frontUserService.register(userEntity);
        return registerMap;
    }

    @RequestMapping(value = "/yaoqing")
    public ModelAndView yaoQing(@RequestParam(value = "referId") String referId, HttpServletRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        // 存放在二维码中的内容
        String text = "http://" + request.getServerName() + ":" + request.getServerPort() + "/front/user/register?referId=" + referId;
        // 嵌入二维码的图片路径
        String imgPath = path + filePatten + "/4.jpg";
        // 生成的二维码的路径及名称
        String currentTimeMillis = System.currentTimeMillis() + ".jpg";
        String destPath = path + filePatten + "/" + currentTimeMillis;
        //生成二维码
        QRCodeUtil.encode(text, imgPath, destPath, true);
        //二维码
        String image001 = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + filePatten + "/" + currentTimeMillis;
        modelAndView.addObject("currentTimeMillis", currentTimeMillis);
        modelAndView.addObject("image001", image001);
        modelAndView.addObject("registerPath", text);
        modelAndView.setViewName("web/erWeiMa");
        return modelAndView;
    }

    @RequestMapping("/lowerList")
    @ResponseBody
    public String lowerList(@RequestParam("aoData") String aoData, @RequestParam("type") String type, HttpSession session) {
        PageResult pr = new PageResult(aoData);

        JSONArray jsonArray = new JSONArray();

        // 从数据库查询，这里返回的的allUser就已经分页成功了
        List<UserEntity> entities = null;
        UserEntity userEntity = (UserEntity) session.getAttribute("userEntity");
        entities = frontUserService.findLowerUsers(userEntity.getId());

        PageInfo<UserEntity> page = new PageInfo<>(entities);

        for (Object obj : entities) {
            UserEntity entity = (UserEntity) obj;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("phone", entity.getPhone());
            if (entity.getUsername() == null || entity.getUsername() == "") {
                jsonObject.put("username", "");
            } else {
                jsonObject.put("username", entity.getUsername());
            }

            if (entity.getEmail() == null || entity.getEmail() == "") {
                jsonObject.put("email", "");
            } else {
                jsonObject.put("email", entity.getEmail());
            }


            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho() + 1) + ",\"iTotalRecords\":" + page.getTotal() + ",\"iTotalDisplayRecords\":" + page.getTotal() + ",\"aaData\":" + jsonArray.toString() + "}";

        return json;
    }

    @RequestMapping(value = "/sureLogin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> login(UserEntity userEntity, HttpSession httpSession) {
        Map<String, Object> loginMap = frontUserService.login(userEntity);
        if (loginMap.get("isSuccess").equals("true")) {
            httpSession.setAttribute("userEntity", loginMap.get("userEntity"));
        }
        return loginMap;
    }


    @RequestMapping(value = "/lowerUsers")
    public ModelAndView lowerUsers(HttpServletRequest request, HttpSession httpSession) {
        /*UserEntity userEntity = (UserEntity)httpSession.getAttribute("userEntity");
        Integer id = userEntity.getId();
        int pageSize = PageUtil.getPage(request,"pageSize") ;
        int pageNum = PageUtil.getPage(request,"pageNum") ;
        PageInfo pageInfo= frontUserService.getLowerUsers(id,pageNum,pageSize);

        List list = pageInfo.getList();*/

        ModelAndView mv = new ModelAndView();
        /*mv.addObject("lowerUsersList",list);*/
        mv.setViewName("web/lowerUsers");
        return mv;
    }

    @RequestMapping(value = "/login")
    public String loginPath() {
        return "web/login";
    }

    @RequestMapping(value = "/register")
    public ModelAndView register(@RequestParam(value = "referId", required = false) String referId) {
        if (StringUtils.isBlank(referId)) {
            ParaEntity paraEntity = paraService.findByParaId("defaultUser");
            referId = String.valueOf(paraEntity.getSequno());
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("web/register");
        modelAndView.addObject("referId", referId);
        return modelAndView;
    }

    @RequestMapping(value = "/index")
    public String commodity() {
        return "index";
    }

    /**
     * 跳转到忘记密码页面
     *
     * @return 忘记密码页面路径
     */
    @RequestMapping(value = "/forgetPassword")
    public ModelAndView forgetPassword() {

        ModelAndView modelAndView = new ModelAndView();
        List<ProblemEntity> allProblemEntity = frontUserService.findAllProblem();
        modelAndView.setViewName("web/forgetPassword");
        modelAndView.addObject("problemList", allProblemEntity);

        return modelAndView;
    }

    /**
     * 跳转到修改密码页面
     *
     * @return 忘记密码页面路径
     */
    @RequestMapping(value = "/updatePasswordByUserId")
    public ModelAndView updatePasswordByUserId(@RequestParam(value = "id", required = false) Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("id", id);
        modelAndView.setViewName("web/updatePassword");
        return modelAndView;
    }

    /**
     * 安全问题验证
     *
     * @param userEntity 用户信息（phone,problem,answer）
     * @return userId
     */
    @ResponseBody
    @RequestMapping(value = "/verification")
    public Map<String, Object> verification(UserEntity userEntity) {
        return frontUserService.verificationByProblem(userEntity);
    }

    /**
     * 重置密码
     *
     * @param userEntity 用户信息（phone,problem,answer）
     * @return 修改结果
     */
    @ResponseBody
    @RequestMapping(value = "/updatePassword")
    public Integer updatePassword(UserEntity userEntity) {
        return frontUserService.updatePassWdById(userEntity);
    }

}
